var express = require('express');
var router = express.Router();
var request = require('request');

var CommonJS = require('../../common/common');
var DBConfig = require('../../db/dbconfig');
var mysql = require('mysql');
var pool = mysql.createPool(DBConfig.mysql2);

//添加一项优惠券
router.get('/jkyx/pc/coupon-add',function(req,res,next){
    let param = req.query || '';
    param.start_time = CommonJS.getNowFormatDate(param.start_time);
    param.end_time = CommonJS.getNowFormatDate(param.end_time);
    param.valid_start = CommonJS.getNowFormatDate(param.valid_start);
    param.valid_end = CommonJS.getNowFormatDate(param.valid_end);
    pool.getConnection(function(err,connection){
        if(err){
			res.end(JSON.stringify({
     			msg: '数据库连接失败',
     			status:'101'
     		}));
        }
        connection.query(DBConfig.addCoupon,[param.name,param.quantity,param.person_limit,param.start_time,
            param.end_time,param.valid_start,param.valid_end,param.coupon_rules_id,param.coupon_type,param.release_status,
            param.status,param.promotion_mode,CommonJS.getNowFormatDate()
        ],function(err, result){
            connection.release();
            if(err)
            {
                res.end(JSON.stringify({
                    msg: '添加失败',
                    status:'102',
                    err: err
                }));
            }else{
                let id = result.insertId;
                connection.query(DBConfig.getCoupon,[id],function(err,data){
                    if(err){
                        res.end(JSON.stringify({
                            msg: '数据丢失',
                            status:'102',
                            err: err
                        }));
                    }else{
                        data[0].id = Number(data[0].id);
                        res.end(JSON.stringify({
                            msg: '添加成功',
                            status:100,
                            data:data[0]
                        }));
                    }
                    
                });
                
            }
        });
    });
});

//修改优惠券
router.get('/jkyx/pc/coupon-update',function(req,res,next){
    let param = req.query || '';
    param.start_time = CommonJS.getNowFormatDate(param.start_time);
    param.end_time = CommonJS.getNowFormatDate(param.end_time);
    param.valid_start = CommonJS.getNowFormatDate(param.valid_start);
    param.valid_end = CommonJS.getNowFormatDate(param.valid_end);
    pool.getConnection(function(err,connection){
        if(err){
			res.end(JSON.stringify({
     			msg: '数据库连接失败',
     			status:'101'
     		}));
        }
        connection.query(DBConfig.updateCoupon,[param.name,param.quantity,param.person_limit,param.start_time,
            param.end_time,param.valid_start,param.valid_end,param.coupon_rules_id,param.coupon_type,param.release_status,
            param.status,param.promotion_mode,CommonJS.getNowFormatDate(),param.id,param.id
        ],function(err, result){
            connection.release();
            if(err)
            {
                res.end(JSON.stringify({
                    msg: '修改',
                    status:'102',
                    err: err
                }));
            }else{
                let data = result[1][0];
                data.id = param.id;
                res.end(JSON.stringify({
                    status:100,
                    data:data
                }));
            }
        });
    });
});

//获取一个优惠券
router.get('/jkyx/pc/coupon',function(req,res,next){
    pool.getConnection(function(err,connection){
        if(err){
			res.end(JSON.stringify({
     			msg: '数据库连接失败',
     			status:'101'
     		}));
        }
        let id = req.query.id || '';
        connection.query(DBConfig.getCoupon,[id,id],function(err, result){
            connection.release();
            if(err)
            {
                res.end(JSON.stringify({
                    msg: '查询失败',
                    status:'102',
                    err: err
                }));
            }else{
            		if (result[0].length == 0) {
            			res.end(JSON.stringify({
	                    status:103,
	                    msg: '无优惠信息'
	                }));
            		} else{
            			let data = result[0][0];
	                data.id = id;
	                data.start_time = CommonJS.getNowFormatDate(result[0].start_time);
	                data.end_time = CommonJS.getNowFormatDate(result[0].end_time);
	                data.valid_start = CommonJS.getNowFormatDate(result[0].valid_start);
	                data.valid_end = CommonJS.getNowFormatDate(result[0].valid_end);
	                data.coupon = result[1][0];
	                data.coupon.param = JSON.parse(data.coupon.param);
	                res.end(JSON.stringify({
	                    status:100,
	                    data:data
	                }));	
            		}
            }
        });
    });
});



//优惠券列表
router.get('/jkyx/pc/coupon-list',function(req,res,next){
    pool.getConnection(function(err,connection){
        if(err){
			res.end(JSON.stringify({
     			msg: '数据库连接失败',
     			status:'101'
     		}));
        }
        let param = req.query || '';
        let key = param.keywords;

        let sql = 'select * from coupon where is_del = 0 and name like "%'+key+'%" order by id desc';
        let coutSql = 'select count(*) as totalCount from coupon';
        connection.query(coutSql,function(err, result){
            if(err)
            {
                res.end(JSON.stringify({
                    msg: '查询失败',
                    status:'102',
                    err: err
                }));
            }else{
                let newArray = [];
                if(key)
                {
                    connection.query(sql,function(err, result){
                        connection.release();
                        if(err)
                        {
                            res.end(JSON.stringify({
                                msg: '查询失败',
                                status:'102',
                                err: err
                            }));
                        }else{
                            result.forEach((data,index) => {
                                let end = Date.parse(CommonJS.getNowFormatDate(data.end_time));
                                let now = Date.parse(new Date());
                                if(end < now)
                                {
                                    data.status = 0;
                                }
                                data.id = Number(data.id);
                                data.start_time = CommonJS.getNowFormatDate(data.start_time);
                                data.end_time = CommonJS.getNowFormatDate(data.end_time);
                                data.valid_start = CommonJS.getNowFormatDate(data.valid_start);
                                data.valid_end = CommonJS.getNowFormatDate(data.valid_end);
                                data.add_time = CommonJS.getNowFormatDate(data.add_time);
                                newArray[index] = data;
                            });
                            res.end(JSON.stringify({
                                status:100,
                                data:newArray
                            }));
                        }
                    });
                }else{
                    var totalCount = result[0].totalCount,page = Number(req.query.page),limit = req.query.limit || 20;
                    var totalPage = Math.ceil(totalCount/limit);
                    if(page)
                    {
                        var limitStart = Number(page-1)*limit,limitEnd = page*limit;
                    }else
                    {
                        var limitStart = 0,limitEnd = totalCount;
                    }
                    connection.query(DBConfig.couponList,[limitStart,limitEnd],function(err, result){
                        connection.release();
                        if(err)
                        {
                            res.end(JSON.stringify({
                                msg: '查询失败',
                                status:'102',
                                err: err
                            }));
                        }else{
                            result.forEach((data,index) => {
                                let end = Date.parse(CommonJS.getNowFormatDate(data.end_time));
                                let now = Date.parse(new Date());
                                if(end < now)
                                {
                                    data.status = 0;
                                }
                                data.id = Number(data.id);
                                data.start_time = CommonJS.getNowFormatDate(data.start_time);
                                data.end_time = CommonJS.getNowFormatDate(data.end_time);
                                data.valid_start = CommonJS.getNowFormatDate(data.valid_start);
                                data.valid_end = CommonJS.getNowFormatDate(data.valid_end);
                                data.add_time = CommonJS.getNowFormatDate(data.add_time);
                                newArray[index] = data;
                            });
                            res.end(JSON.stringify({
                                status:100,
                                page:page,
                                limit:limit,
                                totalCount:totalCount,
                                data:newArray
                            }));
                        }
                    });
                }
                
            }
        });
        
    });
});

// 删除一个优惠券
router.get('/jkyx/pc/coupon-del',function(req,res,next){
    pool.getConnection(function(err,connection){
        if(err){
			res.end(JSON.stringify({
     			msg: '数据库连接失败',
     			status:'101'
     		}));
        }
        var id = req.query.id || '';
        connection.query(DBConfig.deleteCoupon,[id],function(err, result){
            connection.release();
            if(err)
            {
                res.end(JSON.stringify({
                    msg: '查询失败',
                    status:'102',
                    err: err
                }));
            }else{
                res.end(JSON.stringify({
                    status:100,
                    msg:"删除成功"
                }));
            }
        });
    });
});
// 启用优惠券
router.get('/jkyx/pc/coupon-open',function(req,res,next){
    pool.getConnection(function(err,connection){
        if(err){
			res.end(JSON.stringify({
     			msg: '数据库连接失败',
     			status:'101'
     		}));
        }
        var id = req.query.id || '';
        connection.query(DBConfig.open_closeCoupon,[1,id],function(err, result){
            connection.release();
            if(err)
            {
                res.end(JSON.stringify({
                    msg: '查询失败',
                    status:'102',
                    err: err
                }));
            }else{
                res.end(JSON.stringify({
                    status:100,
                    msg:"删除成功"
                }));
            }
        });
    });
});
// 停用优惠券
router.get('/jkyx/pc/coupon-close',function(req,res,next){
    pool.getConnection(function(err,connection){
        if(err){
			res.end(JSON.stringify({
     			msg: '数据库连接失败',
     			status:'101'
     		}));
        }
        var id = req.query.id || '';
        connection.query(DBConfig.open_closeCoupon,[0,id],function(err, result){
            connection.release();
            if(err)
            {
                res.end(JSON.stringify({
                    msg: '查询失败',
                    status:'102',
                    err: err
                }));
            }else{
                res.end(JSON.stringify({
                    status:100,
                    msg:"删除成功"
                }));
            }
        });
    });
});



module.exports = router;